package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.auth.vo.SociaUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 社交登录
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> header = new HashMap<>();
        Map<String, String> query = new HashMap<>();

        Map<String, String> map = new HashMap<>();
        map.put("client_id", "2578024513");
        map.put("client_secret", "26cf09a8e44d4017b0aa71568aa1d69e");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", header, query, map);

        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SociaUserVo sociaUserVo = JSON.parseObject(json, SociaUserVo.class);
            R oauth2Login = memberFeignService.oauth2Login(sociaUserVo);
            if (oauth2Login.getCode() == 0) {
                MemberResponseVo data = oauth2Login.getData("data", new TypeReference<MemberResponseVo>() {
                });
                log.info("登录成功，用户：{}",data);
                //TODO 1、默认发的令牌：session=***-，作用于为当前域，（解决子域session共享问题）
                //TODO 2、使用json的序列化方式来序列化对象到redis
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
//                servletResponse.addCookie(new Cookie("JESSIONID","dad));
                //登录成功,跳转到首页
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }


        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }
}
